package com.aizuda.boot.modules.business.feishu;

import com.aizuda.boot.config.properties.FeiShuConfigProperties;
import com.lark.oapi.core.request.EventReq;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.event.CustomEventHandler;
import com.lark.oapi.event.EventDispatcher;
import com.lark.oapi.event.cardcallback.P2CardActionTriggerHandler;
import com.lark.oapi.event.cardcallback.P2URLPreviewGetHandler;
import com.lark.oapi.event.cardcallback.model.*;
import com.lark.oapi.service.im.ImService;
import com.lark.oapi.service.im.v1.model.P2MessageReceiveV1;
import com.lark.oapi.ws.Client;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class CardBack {

    @Resource
    private FeiShuConfigProperties feiShuConfigProperties;

    private static final EventDispatcher EVENT_HANDLER = EventDispatcher.newBuilder("", "")  // 长连接不需要这两个参数，请保持空字符串
            // 监听「卡片回传交互 card.action.trigger」
            .onP2CardActionTrigger(new P2CardActionTriggerHandler() {
                @Override
                public P2CardActionTriggerResponse handle(P2CardActionTrigger event) throws Exception {
                    log.info("[ P2CardActionTrigger access ], data: {}\n", Jsons.DEFAULT.toJson(event.getEvent()));
                    P2CardActionTriggerResponse resp = new P2CardActionTriggerResponse();
                    return resp;
                }
            })
            // 监听「拉取链接预览数据 url.preview.get」
//            .onP2URLPreviewGet(new P2URLPreviewGetHandler() {
//                @Override
//                public P2URLPreviewGetResponse handle(P2URLPreviewGet event) throws Exception {
//                    log.info("[ P2URLPreviewGet access ], data: {}\n", Jsons.DEFAULT.toJson(event.getEvent()));
//                    P2URLPreviewGetResponse resp = new P2URLPreviewGetResponse();
//                    URLPreviewGetInline inline = new URLPreviewGetInline();
//                    inline.setTitle("链接预览测试fromJavaSDK");
//                    resp.setInline(inline);
//                    return resp;
//                }
//            })
            .build();

    @EventListener(ApplicationReadyEvent.class)
    public void cardBack() {
        feiShuConfigProperties.getApps().forEach((item,config)->{
            Client client = new Client.Builder(config.getAppId(), config.getAppSecret())
                    .eventHandler(EVENT_HANDLER)
                    .build();
            client.start();
        });
    }
}